package servlet;
/*
@Date:2025/4/28
*/

import dao.Db;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginAdmin extends GenericServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        final PrintWriter writer = servletResponse.getWriter();
        HttpSession session = servletRequest1.getSession(false);
        String code = servletRequest.getParameter("code");

        if (session == null|| session.getAttribute("code")==null || !session.getAttribute("code").equals(code)) {
            writer.write("<script>alert('验证码错误！');" + "window.location.href='login.html'</script>");
            return;
        }
        final Db db = new Db();
        //收参
        final String admin = servletRequest.getParameter("admin");
        final String password = servletRequest.getParameter("password");
        final Boolean islogin = db.islogin(admin, password);
        System.out.println("islogin = " + islogin);
        if (islogin) {

            session.setAttribute("pass","ok");
            String id = session.getId();
            Cookie cookie = new Cookie("sessionid", id);
            cookie.setMaxAge(10000);
            HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
            servletResponse1.addCookie(cookie);


            servletRequest.getRequestDispatcher("student").forward(servletRequest, servletResponse);
        } else {
            final HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
            servletResponse1.sendRedirect("error.html");

            System.out.println("失败");
        }
    }
}